package customer

import (
	"encoding/json"
	"fmt"
	"server/global"
	CustomerModel "server/model/customer"
	customerReq "server/model/customer/request"
	customerRes "server/model/customer/response"
	LicenseModel "server/model/license"
	"server/utils"
	"strconv"
	"strings"
	"sync"
	"time"
)

func getTypeName(t uint) string {
	if t == 2 {
		return "正式"
	} else {
		return "POC"
	}
}

func getStatus(s uint) string {
	if s == 2 {
		return "已过期"
	} else {
		return "维保中"
	}
}

func getLicenseStatus(l uint) string {
	if l == 1 {
		return "生效中"
	} else {
		return "已作废"
	}
}

func getMT(m uint) string {
	if m == 1 {
		return "付费"
	} else if m == 2 {
		return "免费"
	} else {
		return "未知"
	}
}

func getVL(level uint) string {
	if level == 10 {
		return "未知"
	}
	return fmt.Sprintf("VIP %d", level)
}

// GetCustomerSummary 获取客户汇总
func (cs *CustomerService) GetCustomerSummary() (Analyse customerRes.AnalyseData, err error) {
	customerDB := global.TD27_DB.Model(&CustomerModel.CustomerModel{})

	// 客户类型分析（所有客户）
	var stats []customerRes.CustomerType
	customerDB.Select("type, COUNT(*) AS count").
		Group("type").
		Scan(&stats)
	for _, stat := range stats {
		var customerList []customerRes.Name
		global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
			Select("name").
			Where("type = ?", stat.Type).
			Order("updated_at DESC").
			Find(&customerList)

		item := customerRes.AnalyseItem{
			Value: stat.Count,
			Name:  getTypeName(stat.Type),
			List:  customerList,
		}
		Analyse.CustomerType = append(Analyse.CustomerType, item)
	}

	// 维保数量分析（POC除外的所有客户）
	var ST []customerRes.TechnicalSupport
	global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
		Where("type = ?", 2).
		Select("service_status, COUNT(*) AS count").
		Group("service_status").
		Scan(&ST)

	for _, s := range ST {
		var customerList []customerRes.Name
		global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
			Select("name").
			Where("service_status = ?", s.Status).
			Where("type = ?", 2).
			Order("updated_at DESC").
			Find(&customerList)
		item := customerRes.AnalyseItem{
			Value: s.Count,
			Name:  getStatus(s.Status),
			List:  customerList,
		}
		Analyse.MaintenanceNum = append(Analyse.MaintenanceNum, item)
	}

	// 获取免费/付费维保数量(仅统计维保期内)
	var MT []customerRes.MaintenanceType
	global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
		Select("maintenance_type, COUNT(*) AS count").
		Where("service_status = ?", 1).
		Group("maintenance_type").
		Scan(&MT)

	for _, s := range MT {
		var customerList []customerRes.Name
		global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
			Select("name").
			Where("maintenance_type = ? AND service_status = ?", s.Type, 1).
			Order("updated_at DESC").
			Find(&customerList)
		item := customerRes.AnalyseItem{
			Value: s.Count,
			Name:  getMT(s.Type),
			List:  customerList,
		}
		Analyse.MaintenanceType = append(Analyse.MaintenanceType, item)
	}

	// 客户等级分析（仅统计维保期内）
	var VL []customerRes.VipLevel
	global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
		Select("vip_level, COUNT(*) AS count").
		Where("service_status = ?", 1).
		Group("vip_level").
		Order("vip_level").
		Scan(&VL)

	for _, v := range VL {
		var customerList []customerRes.Name
		global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
			Select("name").
			Where("vip_level = ? AND service_status = ?", v.Level, 1).
			Order("updated_at DESC").
			Find(&customerList)
		item := customerRes.AnalyseItem{
			Value: v.Count,
			Name:  getVL(v.Level),
			List:  customerList,
		}
		Analyse.VipLevel = append(Analyse.VipLevel, item)
	}

	// 获取环境相关数据
	envDB := global.TD27_DB.Model(&CustomerModel.CustomerEnvModel{})
	// 获取不同类型的环境数量
	var env []customerRes.Env
	envDB.Select("env, COUNT(*) AS count").
		Group("env").
		Scan(&env)

	for _, e := range env {
		var customerList []customerRes.Name
		global.TD27_LOG.Debug(fmt.Sprintf("查询有%s环境的客户,", e.Env))
		global.TD27_DB.Model(&CustomerModel.CustomerEnvModel{}).
			Select("customer.name,version").
			Joins("JOIN customer ON customer_env.customer_id = customer.id").
			Where("customer_env.env = ?", e.Env).
			Order("customer.updated_at DESC").
			Find(&customerList)

		global.TD27_LOG.Debug(fmt.Sprintf("查询有%s环境的客户结果：%s,", e.Env, customerList))
		item := customerRes.AnalyseItem{
			Value: e.Count,
			Name:  e.Env,
			List:  customerList,
		}
		Analyse.Env = append(Analyse.Env, item)
	}

	// 获取license相关数据
	licenseDB := global.TD27_DB.Model(&LicenseModel.LicenseModel{})
	// 获取生效中和已作废的license数量
	var license []customerRes.License
	licenseDB.Select("active, COUNT(*) AS count").
		Group("active").
		Scan(&license)
	for _, l := range license {
		item := customerRes.AnalyseItem{
			Value: l.Count,
			Name:  getLicenseStatus(l.Active),
		}
		Analyse.License = append(Analyse.License, item)
	}

	return
}

// GetEnvData 获取环境列表
func (cs *CustomerService) GetEnvData(envSp customerReq.TimeSearchParams) (envAnalyse customerRes.EnvAnalyse, err error) {

	var env []customerRes.Env
	var startTime time.Time
	var endTime time.Time
	if envSp.StartTime != 0 && envSp.EndTime != 0 {
		startTime = time.Unix(envSp.StartTime, 0)
		endTime = time.Unix(envSp.EndTime, 0)
	} else {
		return envAnalyse, fmt.Errorf("起始时间或终止时间不可为空。")
	}

	//// 循环遍历时间范围内的每个月份
	currentTime := startTime
	for currentTime.Before(endTime) || currentTime.Equal(endTime) {
		// 将当前日期格式化为查询所需的字符串格式
		queryDate := currentTime.Format("2006-01-02 15:04:05")
		// 计算下个月的时间
		nextMonth := currentTime.AddDate(0, 1, 0)
		// 确保下个月的时间不超过endtime
		if nextMonth.After(endTime) {
			nextMonth = endTime.AddDate(0, 0, 1).Truncate(8 * time.Hour)
		}
		query := fmt.Sprintf(`
        SELECT
            env,
            GROUP_CONCAT(
                CASE WHEN created_at >= '%s' AND created_at < '%s'
                THEN customer_id ELSE NULL END
            ) AS customer_ids,
            SUM(
                CASE WHEN created_at >= '%s' AND created_at < '%s'
                THEN 1 ELSE 0 END
            ) AS count
        FROM
            customer_env
        GROUP BY
            env
    `, queryDate, nextMonth.Format("2006-01-02 15:04:05"), queryDate, nextMonth.Format("2006-01-02 15:04:05"))

		err := global.TD27_DB.Raw(query).Scan(&env)
		if err != nil {
			global.TD27_LOG.Warn(fmt.Sprintf("%s", err))
		}
		var currentTimestamp int64
		for _, e := range env {
			currentTimestamp = currentTime.UnixNano() / int64(time.Millisecond)

			customerIDStrSlice := strings.Split(e.CustomerIds, ",")
			var customerIDs []int

			for _, idStr := range customerIDStrSlice {
				id, err := strconv.Atoi(idStr)
				if err != nil {
					continue
				}
				customerIDs = append(customerIDs, id)
			}

			if e.Env == "POC环境" {
				customerNames := getCustomers("POC环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Poc = append(envAnalyse.Poc, _data)
			} else if e.Env == "生产环境" {
				customerNames := getCustomers("生产环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Prod = append(envAnalyse.Prod, _data)
			} else if e.Env == "UAT环境" {
				customerNames := getCustomers("UAT环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Uat = append(envAnalyse.Uat, _data)
			} else if e.Env == "测试环境" {
				customerNames := getCustomers("测试环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Test = append(envAnalyse.Test, _data)
			} else if e.Env == "开发环境" {
				customerNames := getCustomers("开发环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Dev = append(envAnalyse.Dev, _data)
			} else if e.Env == "SIT环境" {
				customerNames := getCustomers("SIT环境", customerIDs)
				_data := []interface{}{currentTimestamp, e.Count, customerNames}
				envAnalyse.Sit = append(envAnalyse.Sit, _data)
			}
		}

		// 增加一个月以进行下一次循环
		currentTime = currentTime.AddDate(0, 1, 0)
	}
	return
}

func getCustomers(env string, customerIDs []int) (customerNames []string) {
	if len(customerIDs) == 0 {
		return []string{}
	}
	global.TD27_DB.Model(&CustomerModel.CustomerEnvModel{}).
		Joins("JOIN customer ON customer_env.customer_id = customer.id").
		Where("customer_env.env = ?", env).
		Where("customer.id IN (?)", customerIDs).
		Select("DISTINCT customer.name").
		Find(&customerNames)
	return
}

// GetOnesData 获取ones的数据
func (cs *CustomerService) GetOnesData(onesSp customerReq.TimeSearchParams) (workOrder customerRes.WorkOrder, err error) {

	var startTime time.Time
	var endTime time.Time
	var onesData customerRes.OnesData

	vip1Time := customerRes.VipCostTime{}
	vip2Time := customerRes.VipCostTime{}
	vip3Time := customerRes.VipCostTime{}
	vip4Time := customerRes.VipCostTime{}
	unknowVipTime := customerRes.VipCostTime{}

	vip1Problems := customerRes.ProblemsFailures{
		Level: "VIP 1",
		Type:  "问题",
	}
	vip2Problems := customerRes.ProblemsFailures{
		Level: "VIP 2",
		Type:  "问题",
	}
	vip3Problems := customerRes.ProblemsFailures{
		Level: "VIP 3",
		Type:  "问题",
	}
	vip4Problems := customerRes.ProblemsFailures{
		Level: "VIP 4",
		Type:  "问题",
	}
	unknowProblems := customerRes.ProblemsFailures{
		Level: "N/A",
		Type:  "问题",
	}
	summaryProblems := customerRes.ProblemsFailures{
		Level: "汇总",
		Type:  "问题",
	}

	vip1Failures := customerRes.ProblemsFailures{
		Level: "VIP 1",
		Type:  "故障",
	}
	vip2Failures := customerRes.ProblemsFailures{
		Level: "VIP 2",
		Type:  "故障",
	}

	vip3Failures := customerRes.ProblemsFailures{
		Level: "VIP 3",
		Type:  "故障",
	}

	vip4Failures := customerRes.ProblemsFailures{
		Level: "VIP 4",
		Type:  "故障",
	}

	unknowFailures := customerRes.ProblemsFailures{
		Level: "N/A",
		Type:  "故障",
	}
	summaryFailures := customerRes.ProblemsFailures{
		Level: "汇总",
		Type:  "故障",
	}

	params := customerReq.GraphQLRequest{
		Query: "{    buckets (      groupBy: $groupBy               orderBy: $groupOrderBy      pagination: $pagination      filter: $groupFilter    ) {      key            tasks (        filterGroup: $filterGroup        orderBy: $orderBy        limit: 1000              ) {            key    name    uuid    status {      name      category    }    deadline(unit: ONESDATE)    estimatedHours    remainingManhour    totalEstimatedHours    issueTypeScope {      uuid    }              importantField{ value }          }      }  }",
		Variables: customerReq.QueryAllVariables{
			GroupBy: map[string]interface{}{
				"tasks": struct{}{},
			},
			OrderBy: map[string]string{
				"createTime": "DESC",
			},
			FilterGroup: []customerReq.FilterGroup{
				{
					NameMatch: "[SPT]",
					CreateTimeRange: struct {
						Gte string `json:"gte"`
						Lte string `json:"lte"`
					}{
						Gte: "2024-01-23",
						Lte: "2024-01-23",
					},
				},
			},
			Pagination: struct {
				Limit int `json:"limit"`
			}{
				Limit: 1000,
			},
		},
	}

	if onesSp.StartTime != 0 && onesSp.EndTime != 0 {
		startTime = time.Unix(onesSp.StartTime, 0)
		endTime = time.Unix(onesSp.EndTime, 0)
		params.Variables.FilterGroup[0].CreateTimeRange.Gte = startTime.Format("2006-01-02")
		params.Variables.FilterGroup[0].CreateTimeRange.Lte = endTime.Format("2006-01-02")
	} else {
		return workOrder, fmt.Errorf("起始时间或终止时间不可为空。error: %s", err)
	}

	// 查询工作项列表
	payload, err := utils.StructToJsonStr(params)
	if err != nil {
		return workOrder, err
	}

	reqOptions := utils.APIRequestOptions{
		URL:    global.TD27_CONFIG.Ones.Url,
		Method: "POST",
		Body:   payload,
		Headers: map[string]string{
			"Ones-Auth-Token": global.TD27_CONFIG.Ones.AuthToken,
			"Ones-User-Id":    global.TD27_CONFIG.Ones.UserID,
		},
		QueryParams: map[string]string{
			"t": "group-task-data",
		},
	}

	res, err := utils.MakeAPIRequest(reqOptions)
	global.TD27_LOG.Debug(fmt.Sprintf("请求ones的查询语句: %s", payload))
	global.TD27_LOG.Debug(fmt.Sprintf("ones返回的数据: %s", res))
	if err != nil {
		global.TD27_LOG.Error(fmt.Sprintf("%s", err))
		return workOrder, err
	}

	// 解析 JSON 数据
	err = json.Unmarshal([]byte(res), &onesData)
	taskList := onesData.Data.Buckets[0].Tasks

	// 如果查询结果为空，则不进行展示
	if len(taskList) != 0 {
		// 补充工单的所属客户和工单类型字段
		err = getworkOrderDetailInfo(&taskList)
		if err != nil {
			global.TD27_LOG.Error(fmt.Sprintf("获取工单的详细数据错误，error：%s", err))
		}

		// 获取工单列表，包括不同工单的总数、不同完成状态的数量
		getWorkOderList(&workOrder, &taskList)

		for _, task := range taskList {
			// 用于处理VIP工单分布图表的数据
			if task.TaskType == "问题" {
				switch task.VipLevel {
				case "VIP 1":
					vip1Problems.Total++
					calcCostTime(&task, &vip1Problems.VipCostTime)
				case "VIP 2":
					vip2Problems.Total++
					calcCostTime(&task, &vip2Problems.VipCostTime)
				case "VIP 3":
					vip3Problems.Total++
					calcCostTime(&task, &vip3Problems.VipCostTime)
				case "VIP 4":
					vip4Problems.Total++
					calcCostTime(&task, &vip4Problems.VipCostTime)
				default:
					unknowProblems.Total++
					calcCostTime(&task, &unknowProblems.VipCostTime)
				}
			} else if task.TaskType == "故障" {
				switch task.VipLevel {
				case "VIP 1":
					vip1Failures.Total++
					calcCostTime(&task, &vip1Failures.VipCostTime)
				case "VIP 2":
					vip2Failures.Total++
					calcCostTime(&task, &vip2Failures.VipCostTime)
				case "VIP 3":
					vip3Failures.Total++
					calcCostTime(&task, &vip3Failures.VipCostTime)
				case "VIP 4":
					vip4Failures.Total++
					calcCostTime(&task, &vip4Failures.VipCostTime)
				default:
					unknowFailures.Total++
					calcCostTime(&task, &unknowFailures.VipCostTime)
				}
			}

			if task.Status.Category == "done" {
				switch task.VipLevel {
				case "VIP 1":
					calcCostTime(&task, &vip1Time)
				case "VIP 2":
					calcCostTime(&task, &vip2Time)
				case "VIP 3":
					calcCostTime(&task, &vip3Time)
				case "VIP 4":
					calcCostTime(&task, &vip4Time)
				default:
					calcCostTime(&task, &unknowVipTime)
				}
			}
		}
	}

	// 生成工单处理耗时的数据
	workOrder.VipWorkOrderTime.Level = []string{"VIP 1", "VIP 2", "VIP 3", "VIP 4", "未知"}
	workOrder.VipWorkOrderTime.Lt30 = []int{vip1Time.Lt30, vip2Time.Lt30, vip3Time.Lt30, vip4Time.Lt30, unknowVipTime.Lt30}
	workOrder.VipWorkOrderTime.Gt30Lt90 = []int{vip1Time.Gt30Lt90, vip2Time.Gt30Lt90, vip3Time.Gt30Lt90, vip4Time.Gt30Lt90, unknowVipTime.Gt30Lt90}
	workOrder.VipWorkOrderTime.Gt90 = []int{vip1Time.Gt90, vip2Time.Gt90, vip3Time.Gt90, vip4Time.Gt90, unknowVipTime.Gt90}

	/** 生成工单分析数据 */
	// 计算占比
	summaryProblems.Total = vip1Problems.Total + vip2Problems.Total + vip3Problems.Total + vip4Problems.Total + unknowProblems.Total
	summaryFailures.Total = vip1Failures.Total + vip2Failures.Total + vip3Failures.Total + vip4Failures.Total + unknowFailures.Total
	calcPercentage(&vip1Problems, summaryProblems.Total)
	calcPercentage(&vip2Problems, summaryProblems.Total)
	calcPercentage(&vip3Problems, summaryProblems.Total)
	calcPercentage(&vip4Problems, summaryProblems.Total)

	calcPercentage(&vip1Failures, summaryFailures.Total)
	calcPercentage(&vip2Failures, summaryFailures.Total)
	calcPercentage(&vip3Failures, summaryFailures.Total)
	calcPercentage(&vip4Failures, summaryFailures.Total)

	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip1Problems)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip1Failures)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip2Problems)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip2Failures)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip3Problems)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip3Failures)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip4Problems)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, vip4Failures)

	// 问题&故障工单分析中是否有未知列
	if unknowProblems.Total != 0 || unknowFailures.Total != 0 {
		calcPercentage(&unknowProblems, summaryProblems.Total)
		calcPercentage(&unknowFailures, summaryFailures.Total)
		workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, unknowProblems)
		workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, unknowFailures)
	}

	// 汇总问题&故障工单数量，并计算总占比
	summaryProblems.Lt30 = vip1Problems.Lt30 + vip2Problems.Lt30 + vip3Problems.Lt30 + vip4Problems.Lt30 + unknowProblems.Lt30
	summaryProblems.Gt30Lt90 = vip1Problems.Gt30Lt90 + vip2Problems.Gt30Lt90 + vip3Problems.Gt30Lt90 + vip4Problems.Gt30Lt90 + unknowProblems.Gt30Lt90
	summaryProblems.Gt90 = vip1Problems.Gt90 + vip2Problems.Gt90 + vip3Problems.Gt90 + vip4Problems.Gt90 + unknowProblems.Gt90

	summaryFailures.Lt30 = vip1Failures.Lt30 + vip2Failures.Lt30 + vip3Failures.Lt30 + vip4Failures.Lt30 + unknowFailures.Lt30
	summaryFailures.Gt30Lt90 = vip1Failures.Gt30Lt90 + vip2Failures.Gt30Lt90 + vip3Failures.Gt30Lt90 + vip4Failures.Gt30Lt90 + unknowFailures.Gt30Lt90
	summaryFailures.Gt90 = vip1Failures.Gt90 + vip2Failures.Gt90 + vip3Failures.Gt90 + vip4Failures.Gt90 + unknowFailures.Gt90

	problemsFailuresTotal := summaryProblems.Total + summaryFailures.Total
	summaryProblems.Lt30Proportion = utils.CalcPercentage(summaryProblems.Lt30, summaryProblems.Total)
	summaryProblems.Gt30Lt90Proportion = utils.CalcPercentage(summaryProblems.Gt30Lt90, summaryProblems.Total)
	summaryProblems.Gt90Proportion = utils.CalcPercentage(summaryProblems.Gt90, summaryProblems.Total)
	summaryProblems.TotalProportion = utils.CalcPercentage(summaryProblems.Total, problemsFailuresTotal)

	summaryFailures.Lt30Proportion = utils.CalcPercentage(summaryFailures.Lt30, summaryFailures.Total)
	summaryFailures.Gt30Lt90Proportion = utils.CalcPercentage(summaryFailures.Gt30Lt90, summaryFailures.Total)
	summaryFailures.Gt90Proportion = utils.CalcPercentage(summaryFailures.Gt90, summaryFailures.Total)
	summaryFailures.TotalProportion = utils.CalcPercentage(summaryFailures.Total, problemsFailuresTotal)

	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, summaryProblems)
	workOrder.ProblemsFailuresData = append(workOrder.ProblemsFailuresData, summaryFailures)

	// 如果VIP工单耗时的未知字段均为0，则移除未知这一列
	if workOrder.VipWorkOrderTime.Lt30[3] == 0 &&
		workOrder.VipWorkOrderTime.Gt30Lt90[3] == 0 &&
		workOrder.VipWorkOrderTime.Gt90[3] == 0 {

		workOrder.VipWorkOrderTime.Level = workOrder.VipWorkOrderTime.Level[:len(workOrder.VipWorkOrderTime.Level)-1]

		workOrder.VipWorkOrderTime.Lt30 = workOrder.VipWorkOrderTime.Lt30[:len(workOrder.VipWorkOrderTime.Lt30)-1]
		workOrder.VipWorkOrderTime.Gt30Lt90 = workOrder.VipWorkOrderTime.Gt30Lt90[:len(workOrder.VipWorkOrderTime.Gt30Lt90)-1]
		workOrder.VipWorkOrderTime.Gt90 = workOrder.VipWorkOrderTime.Gt90[:len(workOrder.VipWorkOrderTime.Gt90)-1]

	}

	return
}

// getworkOrderDetailInfo 获取工单的详细信息，比如属于哪个客户、客户的vip等级、工单类型是问题还是故障
func getworkOrderDetailInfo(taskList *[]customerRes.OnesTask) (err error) {
	var wg sync.WaitGroup
	// 设置请求ones接口的并发限制
	maxConcurrency := 20
	concurrency := make(chan struct{}, maxConcurrency)

	var customerResults []customerRes.CustomerResult
	/*
		eg: map[新莱集团:3 浙江壳牌:2 浙江物产:3百视通:3 碧桂园:2 祈福集团:1 联东集团:1 联合利华:4 药明康德:10  视源股份:1 鞍钢:2]
	*/
	var vipLevelMap = make(map[string]int8)

	// 加载VIP列表
	global.TD27_DB.Model(&CustomerModel.CustomerModel{}).
		Select("name,vip_level").
		Find(&customerResults)

	// 处理VIP查询结果
	for _, customer := range customerResults {
		vipLevelMap[customer.Name] = customer.VipLevel
	}

	for index, task := range *taskList {
		wg.Add(1)
		// 占用一个并发槽位
		concurrency <- struct{}{}
		go func(index int, task customerRes.OnesTask) {
			defer func() {
				// 释放一个并发槽位
				<-concurrency
				wg.Done()
			}()

			params := &customerReq.WorkOrderDetailGraphQL{
				Query: "query Task($key: Key) {\n  task(key: $key) {\n    _VgxCMzpr {value\n    }\n _MNd2Svv8 {value\n    }\n }\n}\n",
			}

			params.Variables.Key = task.Key

			payload, err := utils.StructToJsonStr(params)
			if err != nil {
				return
			}

			reqOptions := utils.APIRequestOptions{
				URL:    global.TD27_CONFIG.Ones.Url,
				Method: "POST",
				Body:   payload,
				Headers: map[string]string{
					"Ones-Auth-Token": global.TD27_CONFIG.Ones.AuthToken,
					"Ones-User-Id":    global.TD27_CONFIG.Ones.UserID,
				},
				QueryParams: map[string]string{
					"t": "Task",
				},
			}

			res, err := utils.MakeAPIRequest(reqOptions)
			if err != nil {
				global.TD27_LOG.Error(fmt.Sprintf("转换参数为 JSON 字符串时出错：%s", err))
			}

			global.TD27_LOG.Debug(fmt.Sprintf("工单详细信息：%s", res))
			taskDetail := customerRes.TaskDetailData{}
			err = json.Unmarshal([]byte(res), &taskDetail)
			if err != nil {
				global.TD27_LOG.Error(fmt.Sprintf("解析工单的详细属性错误，error：%s", err))
			}

			global.TD27_LOG.Debug(fmt.Sprintf("工单所属用户：%s，工单类型：%s", taskDetail.Data.Task.VgxCMzpr.Value, taskDetail.Data.Task.MNd2Svv8.Value))
			task.Customer = taskDetail.Data.Task.VgxCMzpr.Value
			task.TaskType = taskDetail.Data.Task.MNd2Svv8.Value

			vipLevel, _ := vipLevelMap[task.Customer]
			if vipLevel == 10 || vipLevel == 0 {
				task.VipLevel = "N/A"
			} else {
				task.VipLevel = fmt.Sprintf("VIP %d", vipLevel)
			}

			(*taskList)[index] = task
		}(index, task)

	}
	wg.Wait()
	return
}

/** GenerateWorkOrderDetails 生成工单列表详情 */
func GenerateWorkOrderDetails(workOrderDesc *customerRes.WorkOrderDesc, task *customerRes.OnesTask) {
	workOrderDesc.Total++
	if task.Status.Category == "done" {
		workOrderDesc.Done++
	} else {
		workOrderDesc.Todo++
	}

	detail := customerRes.WorkOrderDetail{
		Title:    task.Name,
		VipLevel: task.VipLevel,
		Customer: task.Customer,
		Owner:    task.ImportantFields[1].Value,
		Status:   task.Status.Name,
		UUID:     task.UUID,
	}

	workOrderDesc.List = append(workOrderDesc.List, detail)
}

/** 获取工单列表 */
func getWorkOderList(workOrder *customerRes.WorkOrder, taskList *[]customerRes.OnesTask) {
	for _, task := range *taskList {
		switch task.TaskType {
		case "咨询":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Zixun, &task)
		case "巡检":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Xunjian, &task)
		case "文档":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Wendang, &task)
		case "变更":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Biangeng, &task)
		case "部署":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Bushu, &task)
		case "问题":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Wenti, &task)
		case "故障":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Guzhang, &task)
		case "培训":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Peixun, &task)
		case "客户需求":
			GenerateWorkOrderDetails(&workOrder.WorkOrderList.Xuqiu, &task)
		}
	}
}

/** 计算工单的占比情况 */
func calcPercentage(problemsFailures *customerRes.ProblemsFailures, total int) {
	if total == 0 {
		problemsFailures.TotalProportion = "0%"
		return
	}
	if problemsFailures.Total > 0 {
		problemsFailures.TotalProportion = utils.CalcPercentage(problemsFailures.Total, total)
		problemsFailures.Lt30Proportion = utils.CalcPercentage(problemsFailures.Lt30, problemsFailures.Total)
		problemsFailures.Gt30Lt90Proportion = utils.CalcPercentage(problemsFailures.Gt30Lt90, problemsFailures.Total)
		problemsFailures.Gt90Proportion = utils.CalcPercentage(problemsFailures.Gt90, problemsFailures.Total)
	} else {
		// 如果总数为零，设置默认值0%
		problemsFailures.TotalProportion = "0%"
		problemsFailures.Lt30Proportion = "0%"
		problemsFailures.Gt30Lt90Proportion = "0%"
		problemsFailures.Gt90Proportion = "0%"
	}
}

/** 计算工单的耗时情况 */
func calcCostTime(task *customerRes.OnesTask, vipCostTime *customerRes.VipCostTime) {
	if task.EstimatedHours <= 50000 {
		vipCostTime.Lt30++
	} else if task.EstimatedHours < 150000 {
		vipCostTime.Gt30Lt90++
	} else if task.EstimatedHours >= 150000 {
		vipCostTime.Gt90++
	}
}
